﻿using UnityEngine;
using System.Collections;

public class PlayerShip : MonoBehaviour {
	public ObjectPool pool;
	public GameObject playerShip;
	GameObject spawnedShip;
	Vector3 target; // Ship moving towards this
	public float shipSpeed, moveSensitivity;
	public float maxUp, maxDown;
	public bool enabled;
	// Use this for initialization
	void Start () {
		//spawnShip ();
		target = transform.position;
	}

	void spawnShip() {
		spawnedShip = pool.spawnFromPool ();
		spawnedShip.transform.position = transform.position;
	}

	public void setObjectPool(ObjectPool pool) {
		this.pool = pool;
	}

	// Update is called once per frame
	void Update () {
		if(enabled) {
			if(target.y > maxUp) {
				target = new Vector3(target.x, maxUp, target.z);
			}
			if(target.y < maxDown) {
				target = new Vector3(target.x, maxDown, target.z);
			}

			if(Input.GetKey(KeyCode.W)) {
				target += new Vector3(0f, moveSensitivity, 0f);
			}
			if(Input.GetKey(KeyCode.S)) {
				target -= new Vector3(0f, moveSensitivity, 0f);
			}
			if(Input.GetKey(KeyCode.A)) {
				target += new Vector3(moveSensitivity, 0f, 0f);
			}
			if(Input.GetKey(KeyCode.D)) {
				target -= new Vector3(moveSensitivity, 0f, 0f);
			}
			if(spawnedShip != null) {
				if(spawnedShip.activeSelf) {
					spawnedShip.transform.position = Vector3.MoveTowards (spawnedShip.transform.position, target, shipSpeed * Time.deltaTime);
				}
			} else {
				target = transform.position;
				spawnShip ();
			}
		} else {
			if(spawnedShip != null) {
				pool.pushToPool(spawnedShip);
				spawnedShip = null;
			}
		}
	}
}
